package com.lanchetech.admin.service.impl;


import com.alibaba.excel.util.CollectionUtils;
import com.lanchetech.admin.service.MarketingService;
import com.lanchetech.bean.request.*;
import com.lanchetech.bean.response.*;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.*;
import com.lanchetech.common.enums.*;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.DaoService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.service.QuartzService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.lanchetech.common.constants.JypConstant.MAX_AMOUNT;

@Service
public class MarketingServiceImpl implements MarketingService {
    @Autowired
    KillActivityMapper killActivityMapper;

    @Autowired
    KillSkuMapper killSkuMapper;

    @Autowired
    CoinRewardMapper coinRewardMapper;

    @Autowired
    CoinDeductionMapper coinDeductionMapper;

    @Autowired
    FlashSaleActivityMapper flashSaleActivityMapper;

    @Autowired
    FlashSaleSpuMapper flashSaleSpuMapper;

    @Autowired
    FlashSaleSkuMapper flashSaleSkuMapper;

    @Autowired
    SkuMapper skuMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    PackagesMapper packagesMapper;

    @Autowired
    PackageSkuMapper packageSkuMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    SpuMapper spuMapper;

    @Autowired
    CoinSettingMapper coinSettingMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserVoucherMapper userVoucherMapper;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    SubscribeRecordMapper subscribeRecordMapper;

    @Autowired
    QuartzService quartzService;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    LotteryOpportunityMapper lotteryOpportunityMapper;

    @Override
    public ResultData<BasePageResp<KillActivityResp>> getKillActivityPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<KillActivityResp> list = killActivityMapper.findAllPage(req);
        if (CollectionUtils.isEmpty(list)) {
            return PageHelpUtil.buildPage(list, page);
        }
        Map<Long, Spu> spuMap = daoService.getSpuMap(list.stream().map(KillActivity::getSpuId).collect(Collectors.toList()));
        list.stream().forEach(item -> {
            item.setMainImage(spuMap.get(item.getSpuId()).getMainImage());
            item.setMinPrice(spuMap.get(item.getSpuId()).getMinPrice());
            item.setName(spuMap.get(item.getSpuId()).getName());
        });
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editKillActivity(KillActivityEditVO req) {
        KillActivity killActivity = req.getActivity();
        List<KillSku> skuList = req.getSkuList();
        KillSku min = skuList.stream().min((a, b) -> a.getPrice().compareTo(b.getPrice()) == -1 ? 1 : -1).get();
        killActivity.setMinPrice(min.getPrice());

        if (killActivity.getId() == null) {
            // 新建
            killActivity.setCreatedAt(new Date());
            killActivity.setUpdatedAt(new Date());
            killActivityMapper.insert(killActivity);

            for (KillSku killSku : skuList) {
                killSku.setActivityId(killActivity.getId());
                killSku.setCreatedAt(new Date());
                killSku.setUpdatedAt(new Date());
            }
            killSkuMapper.batchInsert(skuList);
        } else {
            // 编辑
            killActivity.setUpdatedAt(new Date());
            killActivityMapper.updateByPrimaryKeySelective(killActivity);

            if (skuList.get(0).getId() == null) {
                // 先删除之前的sku
                killSkuMapper.deleteByActivityId(killActivity.getId());
                // 全部新建
                for (KillSku killSku : skuList) {
                    killSku.setActivityId(killActivity.getId());
                    killSku.setCreatedAt(new Date());
                    killSku.setUpdatedAt(new Date());
                }
                killSkuMapper.batchInsert(skuList);

            } else {
                for (KillSku killSku : skuList) {
                    killSku.setUpdatedAt(new Date());
                }
                killSkuMapper.updateBatchSelective(skuList);
            }
        }
        return new BaseResp();
    }

    @Override
    public ResultData<KillActivityEditResp> getKillActivityDetail(Long id) {
        KillActivityEditResp resp = new KillActivityEditResp();
        resp.setActivity(killActivityMapper.selectByPrimaryKey(id));
        List<KillSkuVO> list = killSkuMapper.findAllByActivityId(resp.getActivity().getId());
        if (CollectionUtils.isEmpty(list)) {
            resp.setSkuList(list);
            return new ResultData<>(resp);
        }
        Map<Long, Spu> spuMap = daoService.getSpuMap(list.stream().map(KillSku::getSpuId).collect(Collectors.toList()));
        Map<Long, Sku> skuMap = daoService.getSkuMap(list.stream().map(KillSku::getSkuId).collect(Collectors.toList()));
        list.stream().forEach(item -> {
            item.setMainImage(spuMap.get(item.getSpuId()).getMainImage());
            item.setName(spuMap.get(item.getSpuId()).getName());
            item.setMinPrice(spuMap.get(item.getSpuId()).getMinPrice());
            item.setImage(skuMap.get(item.getSkuId()).getImage());
            item.setStock(skuMap.get(item.getSkuId()).getStock());
            item.setStockUnit(skuMap.get(item.getSkuId()).getStockUnit());
            item.setPrice(skuMap.get(item.getSkuId()).getPrice());
            item.setSpecNames(skuMap.get(item.getSkuId()).getSpecNames());
            item.setSpecValues(skuMap.get(item.getSkuId()).getSpecValues());
            item.setCostPrice(skuMap.get(item.getSkuId()).getCostPrice());
        });
        resp.setSkuList(list);
        return new ResultData<>(resp);
    }

    @Override
    public ResultData<BasePageResp<CoinRewardResp>> getCoinRewardPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<CoinRewardResp> list = coinRewardMapper.findAllPage(req);
        if (CollectionUtils.isEmpty(list)) {
            return PageHelpUtil.buildPage(list, page);
        }
        Map<Long, Spu> spuMap = daoService.getSpuMap(list.stream().map(CoinRewardResp::getSpuId).collect(Collectors.toList()));
        list.stream().forEach(item -> {
            item.setMainImage(spuMap.get(item.getSpuId()).getMainImage());
            item.setMinPrice(spuMap.get(item.getSpuId()).getMinPrice());
            item.setName(spuMap.get(item.getSpuId()).getName());
        });
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editCoinReward(List<CoinReward> req) {
        for (CoinReward coinReward : req) {
            // 先判断此商品是否已经设置，如果已经设置，就直接编辑
            CoinReward result = coinRewardMapper.findOneBySpuId(coinReward.getSpuId());
            if (result != null) {
                coinReward.setId(result.getId());
            }
            if (coinReward.getId() == null) {
                // 创建
                coinReward.setCreatedAt(new Date());
                coinReward.setUpdatedAt(new Date());
                coinRewardMapper.insert(coinReward);
            } else {
                // 编辑
                coinReward.setUpdatedAt(new Date());
                coinRewardMapper.updateByPrimaryKeySelective(coinReward);
            }
        }
        return new BaseResp();
    }

    @Override
    public BaseResp deleteCoinReward(Long id) {
        coinRewardMapper.deleteByPrimaryKey(id);
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<CoinDeductionResp>> getCoinDeductionPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<CoinDeductionResp> list = coinDeductionMapper.findAllPage(req);
        if (CollectionUtils.isEmpty(list)) {
            return PageHelpUtil.buildPage(list, page);
        }
        Map<Long, Spu> spuMap = daoService.getSpuMap(list.stream().map(CoinDeductionResp::getSpuId).collect(Collectors.toList()));
        list.stream().forEach(item -> {
            item.setMainImage(spuMap.get(item.getSpuId()).getMainImage());
            item.setMinPrice(spuMap.get(item.getSpuId()).getMinPrice());
            item.setName(spuMap.get(item.getSpuId()).getName());
        });
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editCoinDeduction(List<CoinDeduction> req) {
        for (CoinDeduction coinDeduction : req) {
            // 先判断此商品是否已经设置，如果已经设置，就直接编辑
            CoinDeduction result = coinDeductionMapper.findOneBySpuId(coinDeduction.getSpuId());
            if (result != null) {
                coinDeduction.setId(result.getId());
            }
            if (coinDeduction.getId() == null) {
                // 创建
                coinDeduction.setCreatedAt(new Date());
                coinDeduction.setUpdatedAt(new Date());
                coinDeductionMapper.insert(coinDeduction);
            } else {
                // 编辑
                coinDeduction.setUpdatedAt(new Date());
                coinDeductionMapper.updateByPrimaryKeySelective(coinDeduction);
            }
        }
        return new BaseResp();
    }

    @Override
    public BaseResp editCoinSetting(CoinSetting coinSetting) {
        if (coinSetting.getId() == null) {
            coinSetting.setCreatedAt(new Date());
            coinSetting.setUpdatedAt(new Date());
            coinSettingMapper.insert(coinSetting);
        } else {
            coinSetting.setUpdatedAt(new Date());
            coinSettingMapper.updateByPrimaryKey(coinSetting);
        }
        redisTemplate.delete("CoinSetting");
        return new BaseResp();
    }

    @Override
    public BaseResp deleteCoinSetting(Long id) {
        coinSettingMapper.deleteByPrimaryKey(id);
        redisTemplate.delete("CoinSetting");
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<CoinSetting>> getCoinSettingPage(BasePageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<CoinSetting> list = coinSettingMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp deleteCoinDeduction(Long id) {
        coinDeductionMapper.deleteByPrimaryKey(id);
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<FlashSaleActivity>> getFlashSalePage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<FlashSaleActivity> list = flashSaleActivityMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<FlashSaleEditResp> getFlashSaleDetail(Long id) {
        FlashSaleEditResp resp = new FlashSaleEditResp();
        resp.setActivity(flashSaleActivityMapper.selectByPrimaryKey(id));
        resp.setSpuList(flashSaleSpuMapper.findAllByActivityId(id));
        resp.setSkuList(flashSaleSkuMapper.findAllByActivityId(id));
        return new ResultData<>(resp);
    }

    @Override
    public ResultData<BasePageResp<SubscribeRecordVO>> getSubscribeRecordPage(SubscribeRecordPageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<SubscribeRecordVO> list = subscribeRecordMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            List<FlashSaleSpu> flashSaleSpus = flashSaleSpuMapper.findAllByIdIn(list.stream().map(SubscribeRecordVO::getRelateId).collect(Collectors.toList()));
            Map<Long, FlashSaleSpu> flashSaleSpuMap = new HashMap<>();
            flashSaleSpus.stream().forEach(item -> {
                flashSaleSpuMap.put(item.getId(), item);
            });
            List<FlashSaleActivity> flashSaleActivities = flashSaleActivityMapper.findAllByIdIn(list.stream().map(SubscribeRecordVO::getActivityId).collect(Collectors.toList()));
            Map<Long, FlashSaleActivity> flashSaleActivityMap = new HashMap<>();
            flashSaleActivities.stream().forEach(item -> {
                flashSaleActivityMap.put(item.getId(), item);
            });

            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(SubscribeRecordVO::getUserId).collect(Collectors.toList()));
            list.stream().forEach(item -> {
                item.setUserAvatar(userMap.get(item.getUserId()).getAvatar());
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
                item.setFlashSaleSpu(flashSaleSpuMap.get(item.getRelateId()));
                item.setFlashSaleActivity(flashSaleActivityMap.get(item.getActivityId()));
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editFlashSale(FlashSaleEditVO req) {
        FlashSaleActivity activity = req.getActivity();
        List<FlashSaleSpu> spuList = req.getSpuList();
        List<FlashSaleSku> skuList = req.getSkuList();
        long[] deleteList = req.getDeleteList();

        //活动库存不能高于商品库存
        if (!CollectionUtils.isEmpty(skuList)) {
            Map<Long, Sku> skuMap = skuMapper.findAllByIds(skuList.stream().map(FlashSaleSku::getSkuId).collect(Collectors.toList())).stream().collect(Collectors.toMap(Sku::getId, Sku -> Sku));
            for (FlashSaleSku flashSaleSku : skuList) {
                Sku sku = skuMap.get(flashSaleSku.getSkuId());
                if (flashSaleSku.getStock().compareTo(sku.getStock()) > 0) {
                    return new BaseResp(ResultCode.SKU_STOCK_NOT_ENOUGH, "sku编号" + flashSaleSku.getSkuId() + "库存为：" + sku.getStock());
                }
            }
        }

        Map<Long, Spu> spuMap = spuMapper.findAllByIds(skuList.stream().map(FlashSaleSku::getSpuId).collect(Collectors.toList())).stream().collect(Collectors.toMap(Spu::getId, Spu -> Spu));

        if (activity.getId() == null) {
            // 创建
            activity.setCreatedAt(new Date());
            activity.setUpdatedAt(new Date());
            activity.setDeleted(DeletedEnum.DEFAULT.getStatus());
            flashSaleActivityMapper.insert(activity);

            for (FlashSaleSpu flashSaleSpu : spuList) {
                flashSaleSpu.setActivityId(activity.getId());
                flashSaleSpu.setCreatedAt(new Date());
                flashSaleSpu.setUpdatedAt(new Date());
                flashSaleSpu.setSales(0);
                if (spuMap.containsKey(flashSaleSpu.getSpuId())) {
                    flashSaleSpu.setRid(spuMap.get(flashSaleSpu.getSpuId()).getRid());
                }
            }
            flashSaleSpuMapper.batchInsert(spuList);

            for (FlashSaleSku flashSaleSku : skuList) {
                flashSaleSku.setActivityId(activity.getId());
                flashSaleSku.setSales(0);
                flashSaleSku.setCreatedAt(new Date());
                flashSaleSku.setUpdatedAt(new Date());
            }
            flashSaleSkuMapper.batchInsert(skuList);
        } else {
            // 编辑
            activity.setUpdatedAt(new Date());
            flashSaleActivityMapper.updateByPrimaryKeySelective(activity);

            // spu
            List<FlashSaleSpu> newSpuList = new ArrayList<>();
            List<FlashSaleSpu> updateSpuList = new ArrayList<>();
            for (FlashSaleSpu flashSaleSpu : spuList) {
                if (flashSaleSpu.getId() == null) {
                    flashSaleSpu.setActivityId(activity.getId());
                    flashSaleSpu.setCreatedAt(new Date());
                    flashSaleSpu.setUpdatedAt(new Date());
                    flashSaleSpu.setSales(0);
                    if (spuMap.containsKey(flashSaleSpu.getSpuId())) {
                        flashSaleSpu.setRid(spuMap.get(flashSaleSpu.getSpuId()).getRid());
                    }
                    newSpuList.add(flashSaleSpu);
                } else {
                    flashSaleSpu.setUpdatedAt(new Date());
                    updateSpuList.add(flashSaleSpu);
                }
            }
            if (newSpuList.size() > 0) {
                flashSaleSpuMapper.batchInsert(newSpuList);
            }
            if (updateSpuList.size() > 0) {
                flashSaleSpuMapper.updateBatchSelective(updateSpuList);
            }

            //sku
            List<FlashSaleSku> newSkuList = new ArrayList<>();
            List<FlashSaleSku> updateSkuList = new ArrayList<>();
            for (FlashSaleSku flashSaleSku : skuList) {
                if (flashSaleSku.getId() == null) {
                    flashSaleSku.setActivityId(activity.getId());
                    flashSaleSku.setCreatedAt(new Date());
                    flashSaleSku.setUpdatedAt(new Date());
                    flashSaleSku.setSales(0);
                    newSkuList.add(flashSaleSku);
                } else {
                    flashSaleSku.setUpdatedAt(new Date());
                    updateSkuList.add(flashSaleSku);
                }
            }
            if (newSkuList.size() > 0) {
                flashSaleSkuMapper.batchInsert(newSkuList);
            }
            if (updateSkuList.size() > 0) {
                flashSaleSkuMapper.updateBatchSelective(updateSkuList);
            }

            if (!ArrayUtils.isEmpty(deleteList)) {
                flashSaleSpuMapper.deleteByActivityIdAndSpuList(activity.getId(), deleteList);
                flashSaleSkuMapper.deleteByActivityIdAndSpuList(activity.getId(), deleteList);
            }

            //如果修改了开始时间
            Date startDate = req.getActivity().getStartTime();
            if (startDate != null) {
                Calendar startTime = Calendar.getInstance();
                startTime.setTime(startDate);
                startTime.add(Calendar.MINUTE, -10);
                String startCron = String.format("%d %d %d %d %d ? %d",
                        startTime.get(Calendar.SECOND),
                        startTime.get(Calendar.MINUTE),
                        startTime.get(Calendar.HOUR_OF_DAY),
                        startTime.get(Calendar.DAY_OF_MONTH),
                        startTime.get(Calendar.MONTH) + 1,
                        startTime.get(Calendar.YEAR));
                quartzService.modifyJobTime("FLASH_TRIGGER" + activity.getId().toString(), "FLASH_SALE_NOTIFY", startCron);
            }

        }
        return new BaseResp();
    }


    @Override
    public BaseResp deleteFlashSale(Long id) {
        flashSaleActivityMapper.updateDeletedAndStatusById(DeletedEnum.DELETED.getStatus(), ToggleEnum.OFF.getStatus(), id);
        flashSaleSpuMapper.updateDeletedAndStatusByActivityId(DeletedEnum.DELETED.getStatus(), ToggleEnum.OFF.getStatus(), id);

        //删除定时任务
        TriggerKey triggerKey = TriggerKey.triggerKey("FLASH_TRIGGER" + id, "FLASH_SALE_NOTIFY");
        JobKey jobKey = JobKey.jobKey("FLASH_JOB" + id, "FLASH_SALE_NOTIFY");
        try {
            //关闭定时任务
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器中的任务
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        return new BaseResp();
    }

    @Override
    public BaseResp editPackage(PackageVO req) {
        Packages packages = req.getPackages();
        List<PackageSku> packageSkuList = req.getPackageSkuList();
        Date now = new Date();
        if (req.getPackages().getId() == null) {
            packages.setCreatedAt(now);
            packages.setUpdatedAt(now);
            packages.setDeleted(DeletedEnum.DEFAULT.getStatus());
            packagesMapper.insert(packages);

            packageSkuList.forEach((item) -> {
                item.setActivityId(packages.getId());
                item.setCreatedAt(now);
            });
            packageSkuMapper.batchInsert(packageSkuList);
        } else {
            // 修改只能改套餐和商品，不能删除或添加商品
            packages.setUpdatedAt(new Date());
            packagesMapper.updateByPrimaryKeySelective(packages);

            // 只修改价格和固定数量
            List<PackageSku> updatePackageSkuList = new ArrayList<>();
            packageSkuList.stream().forEach(item -> {
                updatePackageSkuList.add(PackageSku.builder()
                        .id(item.getId())
                        .price(item.getPrice())
                        .count(item.getCount())
                        .build());
            });
            packageSkuMapper.updateBatchSelective(updatePackageSkuList);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<PackageResp> getPackageDetail(Long id) {
        return new ResultData<>(daoService.getPackageDetail(id));
    }

    @Override
    public ResultData<BasePageResp<Packages>> getPackagePage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Packages> list = packagesMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp deletePackage(Long id) {
        packagesMapper.updateDeletedById(DeletedEnum.DELETED.getStatus(), id);
        return new BaseResp();
    }

    @Override
    public BaseResp editCoupon(Coupon coupon) {
        if (coupon.getId() == null) {
            if (coupon.getDiscountAmount().compareTo(MAX_AMOUNT) > 0) {
                return new BaseResp(ResultCode.OUT_OF_AMOUNT_RANGE);
            }

            coupon.setIssuedQuantity(0);
            coupon.setDeleted(DeletedEnum.DEFAULT.getStatus());
            coupon.setCreatedAt(new Date());
            coupon.setUpdatedAt(new Date());
            coupon.setPlatformType(PlatformTypeEnum.PLATFORM.getType());
            coupon.setTenantId(0L);
            couponMapper.insert(coupon);
        } else {
            // 模拟线下发优惠券场景。优惠券创建好后，只可以修改可领取数量、领取时间、启用禁用，其他不可以改。禁用或删除，则已领取的该优惠券全场失效
            Coupon updateCoupon = Coupon.builder()
                    .id(coupon.getId())
                    .title(coupon.getTitle())
                    .stock(coupon.getStock())
                    .startTime(coupon.getStartTime())
                    .endTime(coupon.getEndTime())
                    .status(coupon.getStatus())
                    .updatedAt(new Date())
                    .build();
            couponMapper.updateByPrimaryKeySelective(updateCoupon);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<CouponVO> getCouponDetail(Long id) {
        CouponVO couponVO = new CouponVO();
        Coupon coupon = couponMapper.selectByPrimaryKey(id);
        couponVO.setCoupon(coupon);
        if (CouponTypeEnum.SPU.getType().equals(coupon.getType())) {
            Spu spu = spuMapper.selectByPrimaryKey(coupon.getSpuId());
            couponVO.setSpu(spu);
        }
        return new ResultData<>(couponVO);
    }

    @Override
    public ResultData<BasePageResp<Coupon>> getCouponPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Coupon> list = couponMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp deleteCoupon(Long id) {
        couponMapper.updateDeletedAndUpdatedAtById(DeletedEnum.DELETED.getStatus(), new Date(), id);
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<UserVoucherVO>> getUserVoucherPage(UserVoucherReq req) {
        if (!StringUtils.isEmpty(req.getName())) {
            Shop shop = shopMapper.findOneByShopNameLike(req.getName());
            req.setShopId(shop != null ? shop.getId() : 0L);
        }

        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<UserVoucherVO> list = userVoucherMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(UserVoucherVO::getUserId).collect(Collectors.toList()));
            Map<Long, Shop> shopMap = daoService.getShopMap(list.stream().map(UserVoucherVO::getShopId).collect(Collectors.toList()));
            Map<Long, Spu> spuMap = daoService.getSpuMap(list.stream().map(UserVoucherVO::getSpuId).collect(Collectors.toList()));
            list.stream().forEach(item -> {
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
                item.setAvatar(userMap.get(item.getUserId()).getAvatar());
                item.setShopName(shopMap.get(item.getShopId()).getShopName());
                item.setSpuImage(spuMap.get(item.getSpuId()).getMainImage());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<LotteryOpportunityVO>> getLotteryOpportunityPage(LotteryOpportunityPageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<LotteryOpportunityVO> list = lotteryOpportunityMapper.findAllPage(req);
        if (list.size() > 0) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(LotteryOpportunityVO::getUserId).collect(Collectors.toList()));
            list.stream().forEach(item -> {
                item.setUserAvatar(userMap.get(item.getUserId()).getAvatar());
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }
}